import * as turf from "@turf/turf";
import { Map } from "mapbox-gl";
import { ILayerProps } from "src/types/index";

export default class Base {
  map: Map;
  layerProps: ILayerProps;
  sourceId: string;
  layerIds: string[];
  constructor(map: Map, layerProps: ILayerProps, sourceId: string) {
    this.map = map;
    this.layerProps = layerProps;
    this.sourceId = this.getSourceName(sourceId);
    this.layerIds = []
  }

  getLayerName(name: string) {
    const layerId = this.getName("layer", name);
    this.layerIds.push(layerId)
    return layerId
  }
  getSourceName(name: string) {
    return this.getName("source", name);
  }
  private getName(type: "layer" | "source", name: string) {
    return ["ml", type, this.sourceId, this.layerProps.namePrefix, name]
      .filter(Boolean)
      .join("-");
  }
  get features() {
    return this.getFeatures();
  }

  getFeatures() {
    const source = this.map.getSource(this.sourceId)
    if (source) {
      let data: turf.FeatureCollection = (source as any)._data
      return data.features;
    }
    return [];
  }

  updateFeatures(Features: any, cb?: (v: any) => any) {
    // @ts-ignore
    this.map.getSource(this.sourceId).setData(turf.featureCollection(Features));
    if (typeof cb === "function") {
      cb(this);
    }
  }

  setVisible(visible: boolean) {
    this.layerIds.forEach(layerId => {
      this.map.getLayer(layerId) &&
      this.map.setLayoutProperty(
        layerId,
        "visibility",
        visible ? "visible" : "none"
      );
    })
  }

  clear() {
    // @ts-ignore
    this.map.getSource(this.sourceId).setData(turf.featureCollection([]));
  }
}
